package com.chen.netty.thirdexample;

import com.chen.netty.secondexample.MyClientInitializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * 异步的事件驱动网络应用框架
 */
public class MychatClient {
    public static void main(String[] args) {
        EventLoopGroup workGroup = new NioEventLoopGroup();
        BufferedReader br = null;
        try {
            Bootstrap bootstrap = new Bootstrap();
            Channel channel = bootstrap.group(workGroup).channel(NioSocketChannel.class)
                    .handler(new MychatClientInitializer())
                    .connect("127.0.0.1", 8989).sync().channel();
            br = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                String line = br.readLine() + "\r\n";
                channel.writeAndFlush(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }

            workGroup.shutdownGracefully();
        }
    }
}
